<template>
  <el-form-item label="图片" label-width="120px">
    <div class="file">
      <img :src="imgUrl" v-if="imgUrl" alt="" />
      <span>+</span>
      <input type="file" @change="changeFile" />
    </div>
  </el-form-item>
</template>

<script>
import path from "path";
import { errorAlert } from "../utils/alert";
export default {
  data() {
    return {
      imgUrl: "",
    };
  },
  methods: {

    // 获取文件
    changeFile(e) {
      console.log(e);
      // 取出文件对象
      let file = e.target.files[0];
      //判断大小 1M=1024KB 1KB=1024B   file.size B
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小最大2M");
        return;
      }
      // 判断文件类型 file name: "2.2.2.2.2.jpeg"
      let imgArr = [".jpg", ".jpeg", ".gif", ".png"];
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }
      // 根据文件生成一个图片地址，赋值给imgUrl
      this.imgUrl = URL.createObjectURL(file);
      //将文件存到form.img??????????????
      this.$emit("getFile",file)
    },
  },
};
</script>

<style scoped lang="less">
@import "../less/index.less";
.file {
  width: 150px;
  height: 150px;
  border-radius: 5px;
  border: 1px dashed @primary;
  position: relative;
}
.file input {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
.file span {
  display: inline-block;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 150px;
  font-size: 30px;
}
.file img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
</style>